package cn.mdmm.service.impl.system;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.mdmm.common.MessageConstant;
import cn.mdmm.entity.system.SysRole;
import cn.mdmm.entity.system.SysRoleUser;
import cn.mdmm.entity.system.SysUser;
import cn.mdmm.mapper.system.SysRoleUserMapper;
import cn.mdmm.mapper.system.SysUserMapper;
import cn.mdmm.service.system.SysRoleService;
import cn.mdmm.service.system.SysUserService;
import cn.modoumama.common.exception.RequiredException;
import cn.modoumama.common.exception.ServiceException;
import cn.modoumama.common.utils.PasswordUtils;
import cn.modoumama.service.base.impl.BaseServiceImpl;

@Service
@Transactional
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Long> implements SysUserService {

	@Autowired
	private SysRoleUserMapper roleUsermapper;
	@Autowired
	private SysRoleUserMapper sRoleUserMapper;
	@Autowired
	SysRoleService sysRoleService;

	@Autowired
	public void setMapper(SysUserMapper mapper) {
		setGenericMapper(mapper);
	}

	@Override
	public Integer insert(SysUser record) {
		if (StringUtils.isBlank(record.getPhone())) {
			throw new RequiredException("phone");
		}
		String userPwd = record.getUserPwd();
		record.setUserStatus(1);
		record.setCreateTime(new Date());
		record.setUpdateTime(new Date());
		record.setUserPwd(PasswordUtils.getPassword(record.getUserName(), userPwd));
		return super.insert(record);
	}

	@Override
	public List<SysRoleUser> getRoleIds(Long userId) {
		SysRoleUser roleUser = new SysRoleUser();
		roleUser.setUserId(userId);
		List<SysRoleUser> roleUsers = roleUsermapper.getListByModel(roleUser);
		return roleUsers;
	}

	@Override
	public Set<String> getRole(Long userId) {
		SysRoleUser roleUser = new SysRoleUser();
		roleUser.setUserId(userId);
		List<SysRoleUser> roleUsers = roleUsermapper.getListByModel(roleUser);
		Set<String> rools = new HashSet<>();
		for (SysRoleUser roleUser1 : roleUsers) {
			rools.addAll(sysRoleService.getRolePowers(roleUser1.getRoleId()));
		}
		return rools;
	}

	@Override
	public Set<String> getPowers(Long userId) {
		SysRoleUser roleUser = new SysRoleUser();
		roleUser.setUserId(userId);
		List<SysRoleUser> roleUsers = roleUsermapper.getListByModel(roleUser);
		Set<String> powers = new HashSet<>();
		for (SysRoleUser roleUser1 : roleUsers) {
			powers.addAll(sysRoleService.getRolePowers(roleUser1.getRoleId()));
		}
		return powers;
	}

	@Override
	public Integer updateById(SysUser record) {
		record.setUpdateTime(new Date());
		int flag = super.updateById(record);
		return flag;
	}

	@Override
	public void updateUserPwd(Long id, String userPwd, String newPwd, String confirmPwd) {
		SysUser user = new SysUser();
		user.setId(id);
		SysUser record = findObjectByModel(user);
		if (StringUtils.isNotBlank(userPwd)) {
			userPwd = PasswordUtils.getPassword(record.getUserName(), userPwd);
			if (!userPwd.equals(record.getUserPwd())) {
				throw new ServiceException(MessageConstant.PASSWORD_ERROR);
			}
		}

		if (newPwd.equals(confirmPwd)) {
			newPwd = PasswordUtils.getPassword(record.getUserName(), newPwd);
			record.setUserPwd(newPwd);
			record.setUpdateTime(new Date());
			super.updateById(record);
		} else {
			throw new ServiceException(MessageConstant.NEW_PASSWORD_DIVERSE);
		}
	}

	@Override
	public Integer removeByIds(Long[] userIds) {
		int count = 0;
		for (Long userId : userIds) {
			// 删除用户
			count += removeById(userId);
			// 删除用户和角色的绑定关系
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("userId", userId);
			roleUsermapper.deleteByCondition(condition);
		}
		return count;
	}

	@Override
	public SysUser bindRoleUser(Long userId, Long[] roleIds) {
		SysUser user = null;
		if (userId != null && roleIds != null) {
			user = findById(userId);
			if (user != null) {
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("userId", userId);
				sRoleUserMapper.deleteByCondition(condition);
				for (int i = 0; i < roleIds.length; i++) {
					SysRole role = sysRoleService.getRole(roleIds[i]);
					if (role == null || role.getRoleType() == 0) {
						continue;
					}
					SysRoleUser record = new SysRoleUser();
					record.setRoleId(roleIds[i]);
					record.setUserId(userId);
					sRoleUserMapper.insertModel(record);
				}
			}
		}

		return user;
	}

	@Override
	public List<SysRole> getAllRole(Long userId) {
		SysUser sysUser = findById(userId);
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("roleType", sysUser.getUserType());
		List<SysRole> roles = sysRoleService.findModelsByCondition(condition);
		List<SysRoleUser> roleUsers = getRoleIds(userId);
		// 获取SysRole的id集合
		Set<Long> roleIds = new HashSet<>();
		for (SysRoleUser roleUser1 : roleUsers) {
			roleIds.add(roleUser1.getRoleId());
		}
		// 设置用户是否正在使用
		for (Iterator<SysRole> iterator = roles.iterator(); iterator.hasNext();) {
			SysRole role = iterator.next();
			if (roleIds.contains(role.getRoleId())) {
				role.setIsUse(true);
			} else {
				role.setIsUse(false);
			}
		}
		return roles;
	}

}
